<template>
	<jk-dialog
		:dialog-state="showDialog"
		title="批量了机"
		width="1000px"
		:confirm-btn-loading="confirmBtnLoading"
		:show-content-loading="showLoading"
		@on-cancel="onVisibleChange(false)"
		@on-confirm="onConfirmBtn"
		@on-visible-change="onVisibleChange"
	>
		<el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-width="140px" :show-message="false">
			<div ref="box1">
				<el-tag type="primary" effect="plain" class="margin-bottom-4">
					<span class="el-icon-tickets item-gap"></span>
					<span>基本信息</span>
				</el-tag>
				<jk-card>
					<el-row>
						<el-col :span="12">
							<el-form-item class="margin-bottom-0" label="了机时间" prop="endTime">
								<el-date-picker v-model="ruleForm.endTime" clearable type="datetime" style="width: 100%;" value-format="yyyy-MM-dd HH:mm:ss" placeholder="了机时间" @change="onTimeChange" />
							</el-form-item>
						</el-col>
						<el-col :span="12">
							<el-form-item class="margin-bottom-0" label="了机班次">
								<jk-input v-model="ruleForm.endScheduleShiftName" readonly placeholder=""></jk-input>
							</el-form-item>
						</el-col>
					</el-row>
				</jk-card>
			</div>
			<div ref="box2" class="margin-bottom-4 margin-top-10 flex-between-center">
				<el-tag type="primary" effect="plain">
					<span class="el-icon-tickets item-gap"></span>
					<span>机台明细({{ ruleForm.machineList.length }}台)</span>
				</el-tag>
				<el-tag v-if="errorMachineList.length" type="danger" size="mini">
					<span class="el-icon-warning-outline item-gap-2"></span>
					<span>注：共有<i style="font-size: 14px;font-weight: 500;">{{ errorMachineList.length }}</i>台设备的了机时间小于开台时间!</span>
				</el-tag>
			</div>
			<jk-table
				:data="ruleForm.machineList"
				border
				highlight-hover-row
				highlight-current-row
				:height="dialogTableHeight - 30"
				:row-style="rowClassName"
			>
				<vxe-column title="操作" align="center" field="operation" fixed="left" :width="64">
					<template slot-scope="scope">
						<el-button size="mini" icon="el-icon-remove" type="text" plain @click="ruleForm.machineList.splice(scope.rowIndex, 1)"></el-button>
					</template>
				</vxe-column>
				<vxe-column title="设备" align="center" field="machineName" :width="86">
					<template slot-scope="scope">
						<machineItemInfoPopover :machine-item="scope.row"></machineItemInfoPopover>
					</template>
				</vxe-column>
				<vxe-column title="品种" align="left" field="productName" :min-width="160" />
				<vxe-column title="批号" align="left" field="batchCode" :min-width="140" />
				<!--<vxe-column title="开台锭数" align="right" field="openSpinCount" :width="90"></vxe-column>-->
				<!--<vxe-column title="系数" align="right" field="outputRatio" :width="80"></vxe-column>-->
				<vxe-column title="开台时间" align="center" field="startSystemTime" :width="110">
					<template slot-scope="scope">
						<div class="flex-center" style="flex-direction: column;line-height: 14px;">
							<span>{{ scope.row.startSystemTime ? scope.row.startSystemTime.split(' ')[0] : '' }}</span>
							<span>{{ scope.row.startSystemTime ? scope.row.startSystemTime.split(' ')[1] : '' }}</span>
						</div>
					</template>
				</vxe-column>
				<!--<vxe-column title="开始产量表数" align="right" field="startOutput" :width="100"></vxe-column>-->
				<vxe-column title="产量表数(M)" align="right" field="endOutput" :width="120">
					<template slot-scope="scope">
						<jk-number-input v-model="scope.row.endOutput" size="mini"></jk-number-input>
					</template>
				</vxe-column>
				<vxe-column title="产量表数(kg)" align="right" field="endOutputKg" :width="120">
					<template slot-scope="scope">
						<jk-number-input v-model="scope.row.endOutputKg" size="mini"></jk-number-input>
					</template>
				</vxe-column>
				<!--<vxe-column title="产量采集表数" align="right" field="endSystemOutput" :width="100"></vxe-column>-->
				<vxe-column title="能耗表数" align="right" field="endElectricEnergy" :min-width="120">
					<template slot-scope="scope">
						<jk-number-input v-model="scope.row.endElectricEnergy" size="mini"></jk-number-input>
					</template>
				</vxe-column>
				<!--<vxe-column title="能耗采集表数" align="right" field="endSystemElectricEnergy" :min-width="100"></vxe-column>-->
			</jk-table>
		</el-form>

	</jk-dialog>
</template>

<script>
    import { clearRedundancyKey, formatTime, tipsBar } from '../../../../utils/jk/jk-tool';
    import { workforcemanagementScheduleShiftByTime } from '../../../../api/schedule/empReplacePost';
    import {
        productionPrdNoticeMachineChangeGetMachineDataList,
        productionPrdNoticeMachineOpeningBatchClose,
        productionPrdNoticeMachineOpeningBatchOpening
    } from '../../../../api/production/xsOpen';
    import calHeight from '/src/mixins/cal-dialog-height';
    import machineItemInfoPopover from './machine-info-popover';
    export default {
        mixins: [calHeight],
        components: {
            machineItemInfoPopover
        },
        props: {
            dialogState: {
                type: Boolean,
                default: false
            },
            machineList: {
                type: Array,
                default() {
                    return [];
                }

            }
        },
        data() {
            return {
                errorMachineList: [],
                showLoading: false,
                showDialog: false,
                confirmBtnLoading: false,
                ruleForm: {
                    'outputRatio': 1,
                    'endSpinNumber': null,
                    'openSpinCount': null,
                    'prdNoticeMachineChangeId': null,
                    'endElectricEnergy': null,
                    'startOutput': null,
                    'endScheduleShiftId': null,
                    'endScheduleShiftName': '',
                    'endSystemElectricEnergy': null,
                    'endSystemOutput': null,
                    'endSystemTime': '',
                    'endTime': '',
                    'spinCount': 0, // 机台的设定锭数
                    'usedSpinCount': 0, // 已经开台的锭数
                    'machineList': []
                },
                rules: {
                    endScheduleShiftName: [{ required: true, trigger: 'change' }],
                    endTime: [{ required: true, trigger: 'change' }]
                }
            };
        },
        methods: {
            rowClassName({ row }) {
                if (Date.parse(row.startSystemTime) > Date.parse(this.ruleForm.endTime)) {
                    return {
                        backgroundColor: '#ffeded',
                        color: '#ff4949'
                    };
                }
            },
            onConfirmBtn() {
                this.$refs['ruleForm'].validate(valid => {
                    if (valid) {
                        this.saveRequest();
                    } else {
                        this.$tipsBar(this, 'validator');
                    }
                });
            },
            saveRequest() {
                if (!this.errorMachineList.length) {
                    this.confirmBtnLoading = true;
                    const cpFormData = this.ruleForm.machineList.map(x => {
                        return {
                            // 'endScheduleShiftId': this.ruleForm.endScheduleShiftId,
                            'endSystemTime': this.ruleForm.endSystemTime,
                            'endTime': this.ruleForm.endTime,
                            'outputRatio': x.outputRatio,
                            'openSpinCount': x.openSpinCount,
                            'prdNoticeMachineChangeId': x.prdNoticeMachineChangeId,
                            'endElectricEnergy': x.endElectricEnergy,
                            'endOutput': x.endOutput,
                            'endSystemElectricEnergy': x.endSystemElectricEnergy,
                            'endSystemOutput': x.endSystemOutput,

                            'endOutputKg': x.endOutputKg,
                            'endSystemOutputKg': x.endSystemOutputKg
                        };
                    });
                    productionPrdNoticeMachineOpeningBatchClose(cpFormData).then(res => {
                        this.confirmBtnLoading = false;
                        if (res.data.status === 200) {
                            this.$emit('on-confirm');
                        }
                    });
                } else {
                    tipsBar(this, 'custom', 'warning', `了机时间必须大于开台时间，请检查以下机台: ${this.errorMachineList.map(x => x.machineCode).join('、')}`);
                }
            },
            onVisibleChange(e) {
                if (!e) {
                    this.errorMachineList = [];
                }
                this.$emit('on-visible-change', e);
            },
            onTimeChange() {
                this.$set(this.ruleForm, 'endScheduleShiftId', null);
                this.$set(this.ruleForm, 'endScheduleShiftName', '');
                this.getScheduleShiftForTimeRequest();
                this.getGatherMachineDataRequest();
                this.errorMachineList = this.ruleForm.machineList.filter(x => Date.parse(x.startSystemTime) > Date.parse(this.ruleForm.endTime));
            },
            getScheduleShiftForTimeRequest() {
                if (this.ruleForm.workshopId && this.ruleForm.endTime) {
                    /* return workforcemanagementScheduleShiftByTime({
                        startTime: this.ruleForm.endTime,
                        workshopId: this.ruleForm.workshopId
                    }).then(res => {
                        if (res.data.status === 200) {
                            let resData = res.data.res;
                            if (!resData) {
                                tipsBar(this, 'custom', 'warning', '当前时间未排班，请排班后再操作！');
                                resData = { shiftId: null, shiftName: '' };
                            }
                            this.$set(this.ruleForm, 'endScheduleShiftId', resData.shiftId);
                            this.$set(this.ruleForm, 'endScheduleShiftName', resData.shiftName);
                        }
                    });*/
                }
            },
            // 获取指定机台采集的仪表数据
            getGatherMachineDataRequest() {
                if (this.ruleForm.endTime && this.ruleForm.machineList && this.ruleForm.machineList.length) {
                    return productionPrdNoticeMachineChangeGetMachineDataList({
                        machineIds: this.ruleForm.machineList.map(x => x.machineId),
                        selectDateTime: this.ruleForm.endTime
                    }).then(res => {
                        if (res.data.status === 200) {
                            const resData = res.data.res || [];
                            this.ruleForm.machineList.forEach(x => {
                                resData.forEach(k => {
                                    if (x.machineId === k.machineId) {
                                        // 开台能耗表数，默认等于采集到的实时能耗
                                        this.$set(x, 'endElectricEnergy', k.currentElectricEnergy);
                                        this.$set(x, 'endSystemElectricEnergy', k.currentElectricEnergy);
                                        // 开台产量表数，默认等于采集到的实时产量
                                        this.$set(x, 'endOutput', k.currentOutput);
                                        this.$set(x, 'endSystemOutput', k.currentOutput);

                                        this.$set(x, 'openSpinCount', k.spinCount - k.usedSpinCount);
                                        this.$set(x, 'usedSpinCount', k.usedSpinCount);
                                        this.$set(x, 'spinCount', k.spinCount);

                                        this.$set(x, 'endOutputKg', k.currentOutputKg);
                                        this.$set(x, 'endSystemOutputKg', k.currentOutputKg);
                                    }
                                });
                            });
                        }
                    });
                }
            },
            async getDependentData() {
                this.showLoading = true;
                await this.getScheduleShiftForTimeRequest();
                await this.getGatherMachineDataRequest();
                this.$nextTick(() => {
                    this.$refs.ruleForm.clearValidate();
                });
                this.showLoading = false;
            }
        },
        watch: {
            dialogState(newVal) {
                const cpData = JSON.parse(JSON.stringify(this.machineList)).map(x => {
                    x.prdNoticeMachineChangeId = x.id;
                    x.spinCount = 0;
                    x.usedSpinCount = 0;
                    delete x.id;
                    return clearRedundancyKey(x);
                });
                let workshopIds = cpData.map(x => x.workshopId);
                workshopIds = Array.from(new Set(workshopIds));
                if (workshopIds.length > 1) {
                    tipsBar(this, 'custom', 'warning', '只能操作同一区域内机台!');
                } else {
                    const workshopItem = cpData && cpData.length ? cpData[0] : {};
                    this.$set(this.ruleForm, 'workshopId', workshopItem.workshopId);
                    this.$set(this.ruleForm, 'workshopCode', workshopItem.workshopCode);
                    this.$set(this.ruleForm, 'workshopName', workshopItem.workshopName);
                    this.$set(this.ruleForm, 'machineList', cpData);
                    this.$set(this.ruleForm, 'endSystemTime', formatTime(Date.now()));
                    this.$set(this.ruleForm, 'endTime', formatTime(Date.now()));
                    if (newVal) {
                        this.getDependentData();
                    }
                }
                this.showDialog = newVal;
            }
        }
    };
</script>
